import { NavBar, Popup } from 'antd-mobile'
import classNames from 'classnames'
import styles from './index.module.scss'
import Icon from '@/components/Icon'
import CommentFooter from './CommentFooter'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { useEffect, useState, useRef } from 'react'
import { useStore } from '@/store'
import ContentLoader from 'react-content-loader'
import hljs from 'highlight.js'
// 样式文件可以按照实际的需求选择不同的样式文件
import 'highlight.js/styles/github.css'
import NoComment from './NoComment'
import CommentItem from './CommentItem'
import CommentInput from './CommentInput'
// 严格的高亮 需要在文章发布的时候 就按照需要的格式进行代码添加
const highCode = () => {
  // 配置 highlight.js
  hljs.configure({
    // 忽略未经转义的 HTML 字符
    ignoreUnescapedHTML: true,
  })
  const codes = document.querySelectorAll('.dg-html pre code')
  codes.forEach((code) => {
    hljs.highlightElement(code as HTMLElement)
  })
}
const Article = () => {
  const navigate = useNavigate()
  const { articleDetailStore, commentStore } = useStore()
  const [params] = useSearchParams()
  const id = params.get('id')
  // 触发action函数 发送接口
  useEffect(() => {
    if (id) {
      // 触发文章详情
      articleDetailStore.getDetail(id)
      // 拉取文章评论
      commentStore.getComment('a', id)
      // 代码高亮处理
      highCode()
    }
  }, [])
  const [show, setShow] = useState(false)

  // 获取comment盒子距离顶部的像素值
  const commentRef = useRef<HTMLDivElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)
  // 这里作为判断条件 使用useRef作为临时存储 不能使用useState(异步)
  const isComment = useRef<boolean>(false)
  const scrollToComment = () => {
    // 如果现在已经滚动到了评论区再点击就返回顶部 反之，如果没有滚动到评论区 就去评论区
    if (!isComment.current) {
      const top = commentRef.current?.getBoundingClientRect().top
      wrapperRef.current?.scrollTo({
        top: top! + wrapperRef.current.scrollTop, // 初始的距离顶部的像素值 + 已经滚动的像素值
        behavior: 'smooth',
      })
      isComment.current = true
    } else {
      wrapperRef.current?.scrollTo({
        top: 0,
        behavior: 'smooth',
      })
      isComment.current = false
    }
  }

  // 添加一个loading骨架屏
  // 在数据返回之前先显示loading组件
  if (!articleDetailStore.articleData.art_id) {
    return (
      <ContentLoader
        speed={2}
        width={375}
        height={430}
        viewBox="0 0 375 230"
        backgroundColor="#f3f3f3"
        foregroundColor="#ecebeb">
        <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
        <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
        <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
        <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
        <circle cx="33" cy="69" r="17" />
        <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
        <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
        <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
        <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
        <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
        <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
      </ContentLoader>
    )
  }
  const RenderArticle = () => {
    // 文章详情
    return (
      // wrapper是整个滚动行为发生的父盒子 用它来控制滚动

      <div className="wrapper" ref={wrapperRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{articleDetailStore.articleData.title}</h1>
            <div className="info">
              <span>{articleDetailStore.articleData.pubdate}</span>
              <span>{articleDetailStore.articleData.read_count}阅读</span>
              <span>{articleDetailStore.articleData.comm_count} 评论</span>
            </div>
            <div className="author">
              <img src={articleDetailStore.articleData.aut_photo} />
              <span className="name">
                {articleDetailStore.articleData.aut_name}
              </span>
              <span
                onClick={() => articleDetailStore.followArt()}
                className={classNames(
                  'follow',
                  articleDetailStore.articleData.is_followed ? 'followed' : ''
                )}>
                {articleDetailStore.articleData.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{
                __html: articleDetailStore.articleData.content,
              }}
            />
          </div>
        </div>
        {/* 评论区域  */}
        <div className="comment" ref={commentRef}>
          <div className="comment-header">
            <span>全部评论 {articleDetailStore.articleData.comm_count}</span>
            <span>{articleDetailStore.articleData.like_count} 点赞</span>
          </div>

          <div className="comment-list">
            {/* 没有评论显示占位 有评论显示正常评论列表 */}
            {commentStore.commentData.results.length === 0 ? (
              <NoComment />
            ) : (
              commentStore.commentData.results.map((item) => {
                return <CommentItem key={item.com_id} itemData={item} />
              })
            )}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => navigate(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }>
          <div className="nav-author">
            <img src={articleDetailStore.articleData.aut_photo} />
            <span className="name">
              {articleDetailStore.articleData.aut_name}
            </span>
            <span
              className={classNames(
                'follow',
                articleDetailStore.articleData.is_followed ? 'followed' : ''
              )}>
              {articleDetailStore.articleData.is_followed ? '已关注' : '关注'}
            </span>
          </div>
        </NavBar>
        {/* 文章详情和评论 */}
        <RenderArticle />
        {/* 底部评论栏 */}
        <CommentFooter
          showPopup={() => setShow(true)}
          scrollToComment={scrollToComment}
        />
      </div>
      {/* 准备一个评论弹框 */}
      <Popup
        visible={show}
        style={{
          height: '50vh',
        }}
        onMaskClick={() => setShow(false)}>
        <CommentInput closePopup={() => setShow(false)} />
      </Popup>
    </div>
  )
}

export default observer(Article)
